<?php

namespace bc\service;

use yii;
use bc\service\base\Service;
use bc\model\SpokesmanModel;
use bc\model\ProductModel;
use bc\model\OrderModel;
use bc\util\ImageMergeQrcode;
use bc\model\product\DistributionModel;
use bc\model\product\QrcodeModel;

class SpokesmanService extends Service
{
	
	/**
	 * 最大深度为三级
	 * @var integer
	 */
	protected $maxDeep = 3;
	
	/**
	 * 当前深度
	 * @var integer $currentDeep
	 */
	protected $currentDeep = 0;
	
	protected $muliLevelData = [];
	
	protected $order;
	
	protected $model;
	
	/**
	 * @return the $order
	 */
	public function getOrder()
	{
		return $this->order;
	}

	/**
	 * @param field_type $order
	 */
	public function setOrder($order)
	{
		$this->order = $order;
	}

	public function __construct()
	{
		$this->model = new SpokesmanModel();
	}
	
	
	/**
	 * 生成推广人的二维码
	 * @param int $productId
	 * @param array $user
	 * @return boolean
	 */
	public function createProductQrcode($productId, $user)
	{
		
		$distributionModel = new DistributionModel();
		$distribution = $distributionModel->getRow(['product_id' => $productId]);
		
		$newImage = 'qrcode/product/' . time() . '.jpg';
		
		$data['code'] = uniqid();
		
		//生成普通二维码
		$qrcodePath = $this->createQrcode($productId, $data['code']);
		
		
		$imageMergeQrcode = new ImageMergeQrcode(UPLOAD_PATH . $distribution['template_image'], UPLOAD_PATH . $qrcodePath);
		$imageMergeQrcode->setX(282);
		$imageMergeQrcode->setY(1043);
		$imageMergeQrcode->create(UPLOAD_PATH . $newImage);
		
		$qrcodeModel = new QrcodeModel();
		$qrcodeModel->code = $data['code'];
		$qrcodeModel->user_id = $user['user_id'];
		$qrcodeModel->product_id = $productId;
		$qrcodeModel->qrcode_image = $qrcodePath;
		$qrcodeModel->image = $newImage;
		$qrcodeModel->create_time = date('Y-m-d H:i:s');
		$qrcodeModel->update_time = date('Y-m-d H:i:s');
		
		if(!$qrcodeModel->save())
		{
// 			file_put_contents('/tmp/log/debug.log', "支付错误:".json_encode($qrcodeModel->errors) ."\n". FILE_APPEND);
		}
		
		return true;
	}
	
	
	
	/**
	 * 判断用户是否首次购买
	 * 
	 * @param int $productId
	 * @param array $user
	 * 
	 */
	public function firstBuy($productId, $user)
	{
		$orderModel = new OrderModel();
		$params .= OrderModel::getTableSchema()->name . '.user_id = ' . $user['user_id'];
// 		$params .= ' AND ' . OrderModel::getTableSchema()->name . '.order_status != 5';  //退款订单条件
		$res = $orderModel->firstBuy($productId, $user['user_id']);
		if($res)
			return false;
		else 
			return true;
	}
	
	
	/**
	 * 创建分利关系
	 * @return boolean
	 */
	public function createLevel($productId, $userId, $parenUserId)
	{
		//获取上级关系
		$spokesmanModel = new SpokesmanModel();
		$row = $this->model->getRow(['user_id' => $userId, 'product_id' => $productId]);
		//创建关系
		if(!$row)
		{
			$data['user_id'] = $userId;
			$data['parent_id'] = $parenUserId;
			$data['product_id'] = $productId;
			$data['is_del'] = 0;
			$data['create_time'] = $data['update_time'] = date('Y-m-d H:i:s');
			$this->model->add($data);
			
			return true;
		}
		return false;
		
		
	}
	
	public function getParent($userId, $productId)
	{
		$current = $this->model->getRow(['user_id' => $userId, 'product_id' => $productId]);
		$this->recursionParent($current['parent_id'], $productId);
		return $this->muliLevelData;
	}
	
	
	/**
	 * 获取上级关系 递归 
	 * 
	 */
	protected function recursionParent($userId, $productId)
	{
		$this->currentDeep = $this->currentDeep +1 ;
		
		$row = $this->model->getRow(['user_id' => $userId, 'product_id' => $productId]);
		
		$this->muliLevelData[$this->currentDeep] = $row;
		
		if($row['parent_id'] >0 && $this->currentDeep < $this->maxDeep)
		{
			$this->recursionParent($row['parent_id'], $row['product_id']);
		}
		return false;
	}
	
	
	/**
	 * 创建二维码
	 *
	 * @return string path
	 */
	private function createQrcode($productId, $code)
	{
		$value = Yii::$app->request->hostInfo . '/product/detail?id=' . $productId . '&c=' . $code;
		$errorCorrectionLevel = 'L';
		$matrixPointSize = '5';
	
		$basePath = 'qrcode/product/';
	
		$time = time ();
	
		$filePath = UPLOAD_PATH . $basePath;
		$this->createDir ( $filePath );
		$png_file = $filePath . $time . '.png';
	
		include_once (ROOT_PATH . "/vendor/phpqrcode/phpqrcode.php");
	
		\QRcode::png ( $value, $png_file, $errorCorrectionLevel, $matrixPointSize );
	
		return $basePath . $time . '.png';
	}
	
	/**
	 * 递归创建目录
	 *
	 * @param string $path
	 */
	private function createDir($path)
	{
		if (! file_exists ( $path ))
		{
			$this->createDir ( dirname ( $path ) );
			mkdir ( $path, 0777 );
		}
	}
	
	
}

